import BaseAudioPlayer from "@/common/audio/BaseAudioPlayer";
import { MediaStatus } from "@/common/const";
import type { Station } from "../types/interface";

export default class PlusAudioPlayer extends BaseAudioPlayer {
    private audioCtx: any = null;
    private currentUrl: string = '';

    constructor() {
        super();
    }

    private bindEvents() {
        this.audioCtx.addEventListener('play', () => this.setStatus(MediaStatus.playing));
        this.audioCtx.addEventListener('pause', () => this.setStatus(MediaStatus.paused));
        this.audioCtx.addEventListener('stop', () => this.setStatus(MediaStatus.stoped));
        this.audioCtx.addEventListener('ended', () => this.setStatus(MediaStatus.stoped));
        this.audioCtx.addEventListener('error', (err: any) => {
            this.setStatus(MediaStatus.error);
            const code = err?.code;
        });
    }

    private destroyAudioCtx() {
        if (this.audioCtx) {
            this.audioCtx.stop();
            this.audioCtx.close(); // 释放资源
            this.audioCtx = null;
        }
    }

    play(radio: Station) {
        this.destroyAudioCtx(); // 先销毁旧实例
        this.currentUrl = radio.url;
        this.audioCtx = plus.audio.createPlayer(radio.url);
        this.bindEvents();
        this.audioCtx.play();
    }

    pause() {
        if (this.audioCtx) {
            this.audioCtx.pause();
            this.setStatus(MediaStatus.paused);
        }
    }

    stop() {
        this.destroyAudioCtx();
        // this.currentUrl = 'invalid';
        this.setStatus(MediaStatus.stoped);
    }
}
